package com.grep.base.db;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBUtils {
	static Logger logger = LoggerFactory.getLogger(DBUtils.class);    
	
	private static Properties pro = null ;
	private static ComboPooledDataSource ds = null ;
	
	public static void setPro(Properties pro) {
		DBUtils.pro = pro;
	} 

	/* 
	 * 根据方法名称通过反射获取方法
	 * @param fields
	 * @param methodName
	 * @return 
	 */
	public static Method getMethod(Class clz, String methodName) {
		Method[] methods = clz.getMethods();
		
		Method result = null;
		for (int i = 0; i < methods.length; i++) {
			Method method = methods[i];
			if (method.getName().equals(methodName)) {
				result = method;
				break;
			}
		}
		return result;
	}
	public static Object ToType(Type type, String value){
		return null ;
	}

	/**
	 * 设置c3p0属性
	 */
	public synchronized static void init() {
		if(pro !=null && ds == null){
			logger.info("[init datasource] start init datasource,properties is :{} ",pro) ;
			ds = new ComboPooledDataSource() ;
			ds.setProperties(pro);
			Set set = pro.keySet();
			for(Object str :set){
				if(str!=null){
					String key = str.toString() ;
					String methodName = "set"
						+ key.substring(0, 1).toUpperCase()
						+ key.substring(1);
					Method method = getMethod(ComboPooledDataSource.class,methodName) ;
					if(method !=null){
						Type [] type = method.getParameterTypes() ;
						if(type!=null &&type.length ==1){
							try {
								Object[] objs = null ;
								String value = pro.getProperty(key);
								if(type[0].equals(int.class)){
									objs = new Integer[]{Integer.parseInt(value)} ;
								}else if(type[0].equals(String.class)){
									objs = new String[]{value} ;
								}else if(type[0].equals(long.class)){
									objs = new Long[]{Long.parseLong(value)} ;
								}else if(type[0].equals(double.class)){
									objs = new Double[]{Double.parseDouble(value)} ;
								}else{
									continue ;
								}
								method.invoke(ds, objs);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
			logger.info("[init datasource] end init datasource") ;
		}else{
			logger.error("[init datasource] init datesource failed,please set properties first.");
		}
	}
	/**
	 * 获取数据库连接
	 * @return
	 */
	public synchronized static Connection getConnection(){
		Connection conn = null ;
		try {
			conn = ds.getConnection() ;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if(conn == null){
			logger.error("[get connect] get connect failed.") ;
		}
		return conn ;
	}
	
	/**
	 * 关闭连接
	 * @param conn
	 */
	public static void close(Connection conn){
		if(conn == null){
			return ;
		}
		try {
			conn.close() ;
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 关闭statement
	 * @param sta
	 */
	public static void close(Statement sta){
		if(sta == null){
			return ;
		}
		try {
			sta.close() ;
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 关闭结果集
	 * @param rs
	 */
	public static void close(ResultSet rs){
		if(rs == null){
			return ;
		}
		try {
			rs.close() ;
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 销毁连接
	 */
	public static void destroy(){
		if(ds !=null){
			ds.close() ;
			logger.info(" datasource destroy!");
		}
	}
	/**
	 * 测试查询
	 */
	public static void testQuery(){
		Connection conn = null ;
		Statement sta= null ;
		ResultSet rs = null ;
		try {
			conn = DBUtils.getConnection() ;
			sta =  conn.createStatement() ;
			rs = sta.executeQuery(" select * from web_site ") ;
			while(rs.next()){
				String title = rs.getString("id") ;
				logger.info(" test info table web_site id is :{}",title);
			}
			
		} catch (Exception e){
			e.printStackTrace() ;
		}finally{
			DBUtils.close(rs) ;
			DBUtils.close(sta) ;
			DBUtils.close(conn) ;
		}
	}
}
